import re
from itertools import product, combinations


def parse_number(instr: str) -> float | None:
    """ 获取文本中的数据并进行转化 """
    unit_dict: dict = {'兆': 1e12, '亿': 1e8, '万': 1e4, '千': 1e3,
                       '百': 1e2, '%': 0.01, '‰': 0.001}

    re_search = re.search(r'-?\d+(?:[\d,.]*\d)[兆亿万千百%‰]{0,3}', instr)  # 获取文本中的数字部分
    if not re_search:
        return None
    else:
        searched_string = re_search.group()
        re_search = re.search(r'-?\d+(?:[\d,.]*\d)', searched_string)  # 获取文本中的数字部分
        pos = re_search.span()[1]
        num = float(searched_string[:pos].replace(',', '_'))
        unit = searched_string[pos:]
        if unit:
            for i in unit:
                num *= unit_dict[i]
        return num


def flatten_dict(nested_dict: dict) -> dict:
    """将嵌套字典打平成单层字典"""
    items = []
    for key, value in nested_dict.items():
        if isinstance(value, dict):
            items.extend(flatten_dict(value).items())
            items.append((key, value.get('_')))
        elif key == '' or key == '_' or value == '0':
            pass
        else:
            items.append((key, value))
    return dict(items)


def common_str(s1: str, s2: str, list_suff: list) -> tuple[str, bool]:
    """计算两个字符串的最长公共子序列"""
    list_conn = ['-', '_', '__', '--', '+', '', ':', '：']
    pattern = '|'.join(re.escape(f'{a}{b}') for a, b in product(list_conn, list_suff))

    m, n, cstr, i = len(s1), len(s2), '', 0
    while True:
        if i < min(m, n):
            if s1[i] == s2[i]:
                cstr += s1[i]
            else:
                break
            i += 1
        else:
            break

    if cstr.endswith(('_', '-', '+', ':', '：')):
        cstr = cstr[:-1]
        pos = i - 1
    else:
        pos = i

    if pos == -1:
        return '', False
    list_diff = [re.sub(pattern, '', s1[pos:]) == '', re.sub(pattern, '', s2[pos:]) == '']
    return cstr, all(list_diff)


def is_contain_sml_vars(list_vars: list, list_suff: list) -> bool:
    return any(common_str(var1, var2, list_suff)[1] for var1, var2 in combinations(list_vars, 2))


if __name__ == '__main__':
    instr = '国内生产总值80,976.12元'
    print(parse_number(instr))

    print(common_str('abc_ln_lag1_mom', 'abc_diff_lag4', ['_mom', '_diff', '_lag1', '_lag4', '_ln']))
